package com.service;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * ssh文件复制
 * @author  lgh
 */
@Service
public class SshCopyFileService {

    @Value("${other.ssh.ip}")
    private String sshIp;

    @Value("${other.ssh.port}")
    private String sshPort;

    @Value("${upload.dir}")
    private String desDir;

    private  String run(String command) throws IOException {
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            try {
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
                result += input.nextLine() + "\n";
            }
            result = command + "\n" + result; //加上命令本身，打印出来
        } finally {
            if (input != null) {
                input.close();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }


    /**
     * 复制文件
     * @param src 要复制的文件
     * @return 返回执行后结果
     */
    @SneakyThrows
    public String copy(String src){
        String cmd = "scp -P "+sshPort + " " + src +" " + sshIp +":" + desDir;
        String result = run(cmd);
        return result;
    }

}



